//
//  PersonalViewController.m
//  TextApplication
//
//  Created by dllo on 16/8/27.
//  Copyright © 2016年 yh. All rights reserved.
//

#import "PersonalViewController.h"
#import "TAMacro.h"
#import "PersonalCollectionViewCell.h"
#import "LoginViewController.h"
#import "CollectViewController.h"

#import "UIImageView+WebCache.h"
#import "UIButton+WebCache.h"

#import "SecLoginItems.h"
#import "SecLoginImage.h"

#import "SettingViewController.h"

@interface PersonalViewController () <UICollectionViewDataSource, UICollectionViewDelegate>

@property (nonatomic, strong) UIImageView *backImageView;
@property (nonatomic, strong) UIView *backView;
@property (nonatomic, strong) UILabel *acountLabel;
@property (nonatomic, strong) UIButton *loginButton;
@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) NSArray *textArray;
@property (nonatomic, strong) NSArray *imageArray;
@property (nonatomic, strong) UIButton *setButton;

@property (nonatomic, strong) UIButton *secLoginButton;

@property (nonatomic, strong) SecLoginItems *item;
@end

@implementation PersonalViewController

- (void)viewWillAppear:(BOOL)animated {
    self.navigationController.navigationBar.hidden = YES;
    NSNotificationCenter *ceter = [NSNotificationCenter defaultCenter];
    [ceter addObserver:self selector:@selector(recieveNotice:) name:@"sendValue" object:nil];
    if (self.item.user_images.orig.length == 0) {
        [self.loginButton setImage:[UIImage imageNamed:@"xxipad.png"] forState:UIControlStateNormal];
    } else {
        NSLog(@"%@", self.item.user_images.orig);
        [self.loginButton sd_setImageWithURL:[NSURL URLWithString:self.item.user_images.orig] forState:UIControlStateNormal];
    }
    
    if (self.item.nickname.length == 0) {
        [self.secLoginButton setTitle:@"登录/注册" forState:UIControlStateNormal];
    } else {
    [self.secLoginButton setTitle:self.item.nickname forState:UIControlStateNormal];
    }
    
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    // 通知中心 传值
    [self createView];
}

- (void)recieveNotice:(NSNotification *)notification {
    self.item = [notification.userInfo objectForKey:@"text"];
    NSLog(@"%@", self.item.user_images.orig);
}

- (void)createView {
    self.view.backgroundColor = [UIColor purpleColor];
    self.backImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, (HEIGHT - 44) / 2)];
    self.backImageView.image = [UIImage imageNamed:@"u=873699661,2953818279&fm=21&gp=0.jpg"];
    [self.view addSubview:self.backImageView];
    
    self.backView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, (HEIGHT - 44) / 2)];
    self.backView.backgroundColor = [UIColor blackColor];
    self.backView.alpha = 0.8;
    [self.view addSubview:self.backView];
    
//    self.setButton = [UIButton buttonWithType:UIButtonTypeCustom];
//    self.setButton.frame = CGRectMake(WIDTH - 40, 45, 20, 20);
//    [self.setButton setImage:[UIImage imageNamed:@"13"] forState:UIControlStateNormal];
//    [self.setButton addTarget:self action:@selector(setClick:) forControlEvents:UIControlEventTouchUpInside];
//    [self.backView addSubview:self.setButton];
    
    self.acountLabel = [[UILabel alloc] initWithFrame:CGRectMake(WIDTH / 2 - 40, 30, 80, 50)];
    self.acountLabel.text = @"我的账户";
    self.acountLabel.font = [UIFont systemFontOfSize:14];
    self.acountLabel.textAlignment = 1;
    self.acountLabel.textColor = [UIColor whiteColor];
    [self.backView addSubview:self.acountLabel];
    
    self.loginButton = [UIButton
                        buttonWithType:UIButtonTypeCustom];
    self.loginButton.frame = CGRectMake(WIDTH / 2 - 35, 100, 70, 70);
    self.loginButton.layer.cornerRadius = 35;
    self.loginButton.layer.masksToBounds = YES;
    
    [self.loginButton addTarget:self action:@selector(logClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.backView addSubview:self.loginButton];
    
    self.secLoginButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.secLoginButton.frame = CGRectMake(WIDTH / 2 - 42 + 3, 210, 84, 32);
    self.secLoginButton.layer.cornerRadius = 3;
    self.secLoginButton.titleLabel.font = [UIFont systemFontOfSize:13];
    
    self.secLoginButton.backgroundColor = [UIColor colorWithRed:0.339 green:0.569 blue:0.862 alpha:1.000];
    [self.secLoginButton addTarget:self action:@selector(logClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.backView addSubview:self.secLoginButton];
    
    self.textArray = [NSArray array];
    self.textArray = @[@"我的心愿单", @"清理缓存", @"地址管理", @"良仓客服"];
    self.imageArray = [NSArray array];
    self.imageArray = @[@"1", @"2", @"3", @"4"];
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.itemSize = CGSizeMake(WIDTH / 2 - 1 , (HEIGHT - 44) / 4 - 0.5);
    layout.minimumInteritemSpacing = 1;
    layout.minimumLineSpacing = 1;
    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, (HEIGHT- 44) / 2, WIDTH, (HEIGHT - 44) / 2) collectionViewLayout:layout];
    
    self.collectionView.backgroundColor = [UIColor blackColor];
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    [self.view addSubview:self.collectionView];
    [self.collectionView registerClass:[PersonalCollectionViewCell class] forCellWithReuseIdentifier:@"reuse"];
}

- (void)setClick:(UIButton *)button {



}

- (void)logClick:(UIButton *)button {
    if (self.item.user_images.orig.length == 0) {
        LoginViewController *vc = [[LoginViewController alloc] init];
        UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:vc];
        [self presentViewController:nav animated:YES completion:nil];
    } else {
        SettingViewController *setVC = [[SettingViewController alloc] init];
        setVC.secItem = self.item;
        [self presentViewController:setVC animated:YES completion:nil];
    }
}


- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return 4;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    PersonalCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"reuse" forIndexPath:indexPath];
    cell.backgroundColor = [UIColor whiteColor];
    cell.textLabel.text = self.textArray[indexPath.row];
    [cell.picImageView setImage:[UIImage imageNamed:[NSString stringWithFormat:@"%@", self.imageArray[indexPath.row]]]];
    return cell;
}
- (void)click:(UIButton *)button {
    LoginViewController *vc = [[LoginViewController alloc] init];
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:vc];
    [self presentViewController:nav animated:YES completion:nil];
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 0) {
        CollectViewController *collectVC = [[CollectViewController alloc] init];
        [self.navigationController pushViewController:collectVC animated:NO];
    } else if (indexPath.row == 1) {
        // 保留两位小数(%后".3"三位小数)
        NSString *str = [[NSString stringWithFormat:@"%.2f", [self filePath]] stringByAppendingString:@"M"];
        UIAlertView *AlertView = [[UIAlertView alloc] initWithTitle:@"缓存清理完毕" message:str delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [AlertView show];
        NSLog(@"%f", [self filePath]);

        [self clearFile];
    } else if (indexPath.row == 3) {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"请拨打18304232468" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alertView show];
    } else {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"您还没有登陆,不能进行地址管理" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alertView show];
    }
}

// 计算单个文件夹大小
- (long) fileSizeAtPath:(NSString *)filePath {
    NSFileManager *manager = [NSFileManager defaultManager];
    if ([manager fileExistsAtPath:filePath]) {
        return [[manager attributesOfItemAtPath:filePath error:nil] fileSize];
    }
    return 0;
}
// 计算文件夹大小
- (float)foldSizeAtPath:(NSString *)foldPath {
    NSFileManager *manager = [NSFileManager defaultManager];
    if (![manager fileExistsAtPath:foldPath]) {
        return 0;
    } else {
        NSEnumerator *childFilesEnumerator = [[manager subpathsAtPath:foldPath] objectEnumerator];
        NSString *fileName;
        long long folderSize = 0;
        while ((fileName = [childFilesEnumerator nextObject]) != nil) {
            NSString *fileAbsolutePath = [foldPath stringByAppendingPathComponent:fileName];
            folderSize += [self fileSizeAtPath:fileAbsolutePath];
        }
        return folderSize / (1024.0 * 1024.0);
    }
}

// 显示缓存大小

- (float)filePath {
    NSString *cachPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
    return [self foldSizeAtPath:cachPath];
}

// 清除缓存
- (void)clearFile {
    NSString *cachesPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
    NSArray *files = [[NSFileManager defaultManager] subpathsAtPath:cachesPath];
    for (NSString *str in files) {
        NSError *error = nil;
        NSString *path = [cachesPath stringByAppendingPathComponent:str];
        if ([[NSFileManager defaultManager] fileExistsAtPath:path]) {
            [[NSFileManager defaultManager] removeItemAtPath:path error:&error];
        }
    }
//    [self performSelectorOnMainThread:@selector(clearSuccess) withObject:nil waitUntilDone:YES];
}

//- (void)clearSuccess{
//    UIAlertView *AlertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"缓存清理完毕" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
//    [AlertView show];
//}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
